﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using XsClient.Common;
using XsClient.Models;

namespace XsClient.Parsers
{
    public class DawenxueResolver: BaseResolver
    {

        public override XsSource Source { get => base.Source; protected set => base.Source = value; }

        protected override string listRegex => @"<li><a\s+href=(?<url>.+?)>(?<content>.+?)</a>(?<content>.+?)</li>";

        protected string list2Regex => @"<li><a\s+href=(?<url>.+?)>(?<content>.+?)</a>(?<content>.+?)</li>";

        protected override string chaperRegex => @"<dd><a\s+href=(?<url>.+?)>(?<content>.+?)</a></dd>";
        /// <summary>
        /// 内容
        /// </summary>
        protected override string contextRegex => "<div id=\"content\">";//<div id="content">
        string contextEnd= "<div class=\"bottem2\">";
        /// <summary>
        /// url
        /// </summary>
        private string bookUrlRegex = "https://[^\\s]*\"";
        /// <summary>
        /// 名称
        /// </summary>
        private string nameRegex = "\">[^\\s]*</a>";

        private string authorRegex = "著[^\\s]*</li>";

        string seachRegex = "<td class=\"even\"><a href=\"(?<content>.+?)\" target=\"_blank\">(?<content>.+?)</a></td>";

        string seachNameRegex = "<li><span class=\"s1\">(?<context>.+?)</span></li>";
            //"<td class=\"even\">(?<content>.+?)</td>";


        Regex listRx = null;
        Regex chaperRx = null;

        Regex bookRx = null;
        Regex nameRx = null;
        Regex authorRx = null;
        Regex chaperNameRx = null;
        Regex chaperUrlRx = null;
        Regex seachNameRx = null;

        private string bgqtemp = "window.location=";

        const string baseUrl = "https://www.wucuoxs.com/";

        //protected override string s = "https://www.wucuoxs.com/modules/article/search.php?keyword={0}";

        public DawenxueResolver()
        {
            Name = "大文学";
            InitSource(4, new XsSource() { BaseUrl = baseUrl, Encoding = "utf8", ID = 4, Name = "大文学" });
            seachUrl = Source.BaseUrl + "modules/article/search.php?keyword={0}";
            listRx = new Regex(listRegex);
            chaperRx = new Regex(chaperRegex);
            bookRx = new Regex(bookUrlRegex);
            nameRx = new Regex(nameRegex);
            authorRx = new Regex(authorRegex);
            chaperUrlRx = new Regex("href=[^\\s]*html");
            chaperNameRx = new Regex("\">.*</a>");
            seachNameRx = new Regex(seachNameRegex);
        }
        public override List<BookInfo> Seach(string name)
        {
            string url = string.Format(seachUrl, HttpUtility.UrlEncode(name));
            string htmlStr = Client.GetHtml(url, Source.Encoding);
            return FindSeachBooks(htmlStr);
        }

        private List<BookInfo> FindSeachBooks(string htmlStr)
        {
            List<BookInfo> books = new List<BookInfo>();

            int tbStart = htmlStr.IndexOf("<div class=\"novelslist2\">");
            if (tbStart > 0)
            {
                var collection = seachNameRx.Matches(htmlStr, tbStart);
                if (collection != null && collection.Count > 0)
                {
                    for (int i = 0; i < collection.Count; i += 2)
                    {
                        try
                        {
                            var item = collection[i];
                            var itemAuthor = collection[i + 1];
                            string value = item.Value.Replace("<font color=\"red\">", "").Replace("</font>", "");
                            string value2 = itemAuthor.Value;
                            if (value.IndexOf("href=") < 0)
                                continue;
                            int sid = value.IndexOf("href=\"");
                            int sid2 = value.IndexOf("target=\"_blank\">");
                            string url = value.Substring(sid + 6, sid2 - sid - 8).Trim();
                            string name = value.Substring(sid2 + 16, value.Length - sid2 - 25).Trim();
                            string author = value2.Substring(17, value2.Length - 22).Trim();
                            BookInfo info = new BookInfo()
                            {
                                BaseUrl = url,
                                Name = name,
                                Author = author,
                                SourceID = Source.ID
                            };

                            books.Add(info);
                        }
                        catch (Exception ex)
                        {
                            NewLife.Log.XTrace.WriteException(ex);
                        }
                    }
                    return books;
                }
            }

            return books;

        }

        public override List<BookInfo> FindBooks(string url)
        {
            return base.FindBooks(url);
        }
        public override List<BookInfo> FindBooksByHtml(string html)
        {
            if (html.Contains(bgqtemp))
            {
                string tempkey = html.Substring(html.IndexOf(bgqtemp) + bgqtemp.Length + 2, 50);
                tempkey = tempkey.Substring(0, tempkey.IndexOf("\"") - 1);
                html = Client.GetHtml(baseUrl + tempkey, Source.Encoding);

            }
            var collection = listRx.Matches(html);
            if (collection != null && collection.Count > 0)
            {
                List<BookInfo> books = new List<BookInfo>();
                foreach (Match item in collection)
                {
                    try
                    {
                        string value = item.Value;
                        string url = bookRx.Match(value).Value.Trim('"');
                        string name = nameRx.Match(value).Value.Substring(2).Replace("</a>", "");
                        string author = authorRx.Match(value).Value.Substring(2).Replace("</li>", "");
                        BookInfo info = new BookInfo()
                        {
                            BaseUrl = url,
                            Name = name,
                            Author = author,
                            SourceID = Source.ID
                        };

                        books.Add(info);
                    }
                    catch (Exception ex)
                    {
                        NewLife.Log.XTrace.WriteException(ex);
                    }
                }
                return books;
            }
            return null;
        }

        public override List<ChaperInfo> FindChapers(ref string url)
        {
            string bookUrl = url;
            string htmlStr = Client.GetHtml(ref bookUrl, Source.Encoding);
            if (htmlStr == null)
                return null;
            if (htmlStr.Contains(bgqtemp))
            {
                string tempkey = htmlStr.Substring(htmlStr.IndexOf(bgqtemp) + bgqtemp.Length + 2, 50);
                tempkey = tempkey.Substring(0, tempkey.IndexOf("\"") - 1);
                bookUrl = Source.BaseUrl + tempkey;
                htmlStr = Client.GetHtml(ref bookUrl, Source.Encoding);
            }
            GetBaseUrl(bookUrl);
            url = bookUrl;
            var collection = chaperRx.Matches(htmlStr);
            if (collection != null && collection.Count > 0)
            {
                List<ChaperInfo> chapers = new List<ChaperInfo>();
                int i = 0;
                foreach (Match item in collection)
                {
                    try
                    {
                        string value = item.Value;
                        string itemUrl = chaperUrlRx.Match(value).Value.Substring(6);
                        string nameStr = chaperNameRx.Match(value).Value;
                        string name = null;
                        if (string.IsNullOrEmpty(nameStr))
                        {
                            nameStr = value.Substring(value.IndexOf("title"), value.IndexOf("\">") - value.IndexOf("title"));
                            name = nameStr.Substring(7).Replace("\">", "");
                        }
                        else
                            name = nameStr.Substring(2, nameStr.Length - 6).Replace("\">", "");
                        ChaperInfo chaper = new ChaperInfo() { ID = i++, Url = baseUrl.TrimEnd('/') + "/" + itemUrl, Name = name };
                        chaper.SourceID = Source.ID;
                        chapers.Add(chaper);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                }
                return chapers;
            }
            return null;
        }

        public override string GetContext(string url)
        {
            string htmlStr = Client.GetHtml(url, Source.Encoding);

            int startIndex = htmlStr.IndexOf(contextRegex);
            if (startIndex > 0)
            {
                int endIndex = htmlStr.IndexOf(contextEnd, startIndex + 27);
                if (endIndex > 0)
                    return htmlStr.Substring(startIndex + 27, endIndex - startIndex - 27).Replace("<br>&nbsp;", "").Replace("<br>", "").Replace("<br/>", "\r\n").Replace("&nbsp;", " ").Replace("\n\n", "\r\n").Replace("\r\n\r\n", "\r\n");
                else
                {
                    endIndex = htmlStr.IndexOf("</div>", startIndex + 27);
                    return htmlStr.Substring(startIndex + 27, endIndex - startIndex - 27).Replace("<br>&nbsp;", "").Replace("<br>", "").Replace("<br/>", "\r\n").Replace("&nbsp;", " ").Replace("\n\n", "\r\n").Replace("\r\n\r\n", "\r\n");
                }
            }

            return null;
        }

        Regex urlNameRx = new Regex("<a\\s+href=(?<url>.+?)>(?<content>.+?)</a>");
        public override List<XsUrlInfo> FindBookTypes()
        {
            string htmlStr = Client.GetHtml(baseUrl, Source.Encoding);
            List<XsUrlInfo> urls = new List<XsUrlInfo>();
            string navDiv = "<div class=\"nav\">";
            int navIndex = htmlStr.IndexOf(navDiv);
            if (navIndex > 0)
            {
                int endIndex = htmlStr.IndexOf("</div>", navIndex + 20);
                string navDivHtml = htmlStr.Substring(navIndex + 20, endIndex - navIndex - 18);
                var collection = urlNameRx.Matches(navDivHtml);
                if (collection != null && collection.Count > 0)
                {
                    foreach (Match item in collection)
                    {
                        var str = item.Value;
                        int hrefEnd = str.IndexOf("\"", 10);
                        string url = str.Substring(9, hrefEnd - 9);
                        if (!url.Contains("http"))
                            url = baseUrl + url;
                        string name = str.Substring(hrefEnd + 2, str.Length - 2);
                        var urlInfo = new XsUrlInfo() { SourceID = Source.ID, Name = name, Url = url };
                        urls.Add(urlInfo);
                    }
                }
            }


            return urls;
        }

    }
}
